package com.jerry.security.qq.api;

import org.apache.commons.lang.StringUtils;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

import com.fasterxml.jackson.databind.ObjectMapper;

public class QQImpl extends AbstractOAuth2ApiBinding implements QQ {

	// 获取openid的链接地址
	private static final String URL_GET_OPENID = "https://graph.qq.com/oauth2.0/me?access_token=%s";
	// 获取userinfo的链接地址
	private static final String URL_GET_USERINFO = "https://graph.qq.com/user/get_user_info?oauth_consumer_key=%s&openid=%s";
	// 商户号，永久不能更改
	private String appId;
	// 开放平台为用户分配的唯一性id
	private String openId;
	
	private ObjectMapper objectMapper = new ObjectMapper();
	
	public QQImpl(String accessToken, String appId) {
		// TokenStrategy.ACCESS_TOKEN_PARAMETER 代表发送请求时，将token做为查询参数
		super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);
		this.appId = appId;

		// 获取openid的完整地址
		String url = String.format(URL_GET_OPENID, accessToken);
		// 获取openid请求
		String result = getRestTemplate().getForObject(url, String.class);
		System.out.println(result);
		// 截取 openid
		this.openId = StringUtils.substringBetween(result, "\"openid\":\"", "\"}");
	}

	@Override
	public QQUserInfo getUserInfo() {
		// 获取userinfo的完整地址
		String url = String.format(URL_GET_USERINFO, appId, openId);
		// 获取userinfo请求
		String result = getRestTemplate().getForObject(url, String.class);
		System.out.println(result);
		// 生成 userinfo
		QQUserInfo userInfo = null;
		try {
			userInfo = objectMapper.readValue(result, QQUserInfo.class);
			userInfo.setOpenId(openId);
			return userInfo;
		} catch (Exception e) {
			throw new RuntimeException("获取用户信息失败", e);
		}
	}

}
